from urllib.request import urlopen
from html.parser import HTMLParser
import sys
import re
import pokeparser

class abilityinfo(HTMLParser):
	def __init__(self,url):
		super().__init__()
		self.in_table = self.in_info = self.in_li = self.in_h2 = self.in_effect = self.in_span = self.in_inner = self.in_style = False
		self.info = ''
		self.infos = 0
		self.effect = ''
		self.inners = 0
		self.p = pokeparser.pokeparser()
		self.text = self.p.gettext(url)
	def handle_starttag(self, tag, attrs):
		attrs = dict(attrs)
		if tag == 'tbody':
			self.in_table = True
		elif tag == 'li':
			self.in_li = True
			if self.in_info and self.infos > 0:
				self.info += '/'
		elif tag == 'h2':
			self.in_h2 = True
		elif tag == 'span':
			self.in_span = True
			if attrs.get('class','') == 'type-box-8-inner':
				self.in_inner = True
		elif tag == 'style':
			self.in_style = True
	def handle_data(self, data):
		data = str(data).strip(' \n')
		# 获得基本信息：
		if self.in_table:
			if data == '基本信息':
				self.in_info = True
			elif self.in_info and self.in_li:
				self.info += data
		# 设置效果读取：
		elif self.in_h2:
			if re.search('变更',data) or re.search('黑连的描述',data) or re.search('具有该特性',data) or re.search('名字',data):
				self.in_effect = False
			elif re.search('效果',data):
				self.in_effect = True
		# 获得特性效果：
		elif self.in_effect and data != '':
			if self.in_span == False and self.in_style == False:
				self.effect += data
				self.inners = 0
			elif self.in_inner:
				if self.inners > 0:
					self.effect += '/'
				self.effect += data
				self.inners += 1
	def handle_endtag(self, tag):
		if tag == 'tbody':
			self.in_table = False
			self.in_info = False
			self.infos = 0
		elif tag == 'li':
			self.in_li = False
			self.infos += 1
		if tag == 'h2':
			self.in_h2 = False
		elif tag == 'span':
			self.in_span = False
			self.in_inner = False
		elif tag == 'style':
			self.in_style = False

def test():
	a = abilityinfo(r'https://wiki.52poke.com/zh-hans/%E6%81%B6%E8%87%AD%EF%BC%88%E7%89%B9%E6%80%A7%EF%BC%89')
	a.feed(a.text)
	print(a.info)
	print(a.effect)
	a = abilityinfo(r'https://wiki.52poke.com/zh-hans/%E7%A5%9E%E5%A5%87%E5%AE%88%E6%8A%A4%EF%BC%88%E7%89%B9%E6%80%A7%EF%BC%89')
	a.feed(a.text)
	print(a.info)
	print(a.effect)
	a = abilityinfo(r'https://wiki.52poke.com/zh-hans/%E6%88%98%E6%96%97%E7%9B%94%E7%94%B2%EF%BC%88%E7%89%B9%E6%80%A7%EF%BC%89')
	a.feed(a.text)
	print(a.info)
	print(a.effect)
	a = abilityinfo(r'https://wiki.52poke.com/zh-hans/%E6%8C%81%E4%B9%85%E5%8A%9B%EF%BC%88%E7%89%B9%E6%80%A7%EF%BC%89')
	a.feed(a.text)
	print(a.info)
	print(a.effect)
	a.close()

if __name__ == "__main__":
	test()